package com.liliudong.template.biz.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.template.biz.mapper.sys.SysRoleDeptMapper;
import com.liliudong.template.biz.service.sys.SysRoleDeptService;
import com.liliudong.template.common.entity.sys.SysRoleDept;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * sys角色dept服务impl
 *
 * @author ldli5
 * @date 2024/06/20
 */
@Service
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptMapper, SysRoleDept> implements SysRoleDeptService {

	@Override
	public void saveBatchWithRoleId(Long roleId, List<Long> deptIds) {
		List<SysRoleDept> sysRoleDeptList = deptIds.stream()
				.map(deptId -> {
					SysRoleDept sysRoleDept = new SysRoleDept();
					sysRoleDept.setRoleId(roleId);
					sysRoleDept.setDeptId(deptId);
					return sysRoleDept;
				})
				.collect(Collectors.toList());
		this.saveBatch(sysRoleDeptList);
	}

	@Override
	public void removeByRoleId(Long roleId) {
		this.remove(lambdaQuery().eq(SysRoleDept::getRoleId, roleId).getWrapper());
	}

	@Override
	@Transactional
	public void updateBatchWithRoleId(Long roleId, List<Long> deptIds) {
		this.removeByRoleId(roleId);
		if (CollUtil.isEmpty(deptIds)) {
			this.saveBatchWithRoleId(roleId, deptIds);
		}
	}

	@Override
	public long countByDeptId(Long deptId) {
		return this.count(lambdaQuery().eq(SysRoleDept::getDeptId, deptId).getWrapper());
	}

	@Override
	public Set<Long> listDeptIdsByRoleId(Long roleId) {
		return list(
				lambdaQuery()
						.select(SysRoleDept::getDeptId)
						.eq(SysRoleDept::getRoleId, roleId)
						.getWrapper()
		)
				.stream()
				.map(SysRoleDept::getDeptId)
				.collect(Collectors.toSet());
	}
}
